package test5.lupeng.jf.com.teamdemo.fragment;


import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.activitys.AttentionActivity;
import test5.lupeng.jf.com.teamdemo.activitys.CalendarActivity;
import test5.lupeng.jf.com.teamdemo.activitys.FansActivity;
import test5.lupeng.jf.com.teamdemo.activitys.LoginActivity;
import test5.lupeng.jf.com.teamdemo.activitys.MyMessagesActivity;
import test5.lupeng.jf.com.teamdemo.activitys.MyProblemActivity;
import test5.lupeng.jf.com.teamdemo.activitys.MyShareActivity;
import test5.lupeng.jf.com.teamdemo.activitys.MySignActivity;
import test5.lupeng.jf.com.teamdemo.activitys.PersonMessageActivity;
import test5.lupeng.jf.com.teamdemo.activitys.SettingActivity;
import test5.lupeng.jf.com.teamdemo.bean.request.UpdateProBean;
import test5.lupeng.jf.com.teamdemo.untils.GlideCircleTransform;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;
import test5.lupeng.jf.com.teamdemo.untils.PostMethods;
import test5.lupeng.jf.com.teamdemo.untils.UserInfo;

import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;
import static test5.lupeng.jf.com.teamdemo.R.id.iv_MakeCode;
import static test5.lupeng.jf.com.teamdemo.R.id.rl_sign;

/**
 * 我的
 * Created by C-yx on 2017/7/27.
 */

public class MyselfFragment extends Fragment {
    @BindView(R.id.tv_login)
    TextView tvLogin;
    Unbinder unbinder;
    @BindView(R.id.ll_parent)
    LinearLayout llParent;
    @BindView(R.id.iv_userhead)
    ImageView ivUserhead;
//    @BindView(R.id.rl_photo)
//    RelativeLayout rlPhoto;
//    @BindView(R.id.rl_album)
//    RelativeLayout rlAlbum;
//    @BindView(R.id.rl_cancle)
//    RelativeLayout rlCancle;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    @BindView(R.id.ll_problem)
    LinearLayout llProblem;
    @BindView(R.id.rl_setting)
    RelativeLayout rlSetting;
    @BindView(R.id.iv_MakeCode)
    ImageView ivMakeCode;
    @BindView(R.id.rl_sign)
    RelativeLayout rlSign;
    @BindView(R.id.rl_messages)
    RelativeLayout rlMessages;
    @BindView(R.id.rl_three)
    LinearLayout rlThree;
    @BindView(R.id.rl_goto)
    LinearLayout rlGoto;
    @BindView(R.id.rl_care)
    RelativeLayout rlCare;
    @BindView(R.id.rl_fans)
    RelativeLayout rlFans;
    private BottomSheetBehavior bottomSheetBehavior;
    private String picPath;
    private CustomBottomSheetDialogFragment fragment;
    private View view;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(container.getContext()).inflate(R.layout.myself_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListeners();
    }

    public void initView() {
        //1.当没有用户登录的时候  程序首次进入没有登录记录    2.登录过 本地有登录用户的ID
        if (!UserInfo.userId.equals("")) {
            rlThree.setVisibility(View.VISIBLE);
            getUserInfo(UserInfo.userId);
            ivMakeCode.setImageBitmap(PostMethods.generateBitmap("http://baidu.com", 100, 100));
            fragment = new CustomBottomSheetDialogFragment();
            fragment.setListener(new CustomBottomSheetDialogFragment.Listener() {
                @Override
                public void photo() {
                    //将拍摄的图片存储到固定的路径  获取的是原图   SD卡的路径
                    picPath = Environment.getExternalStorageDirectory().getPath() + "/" + "temp.png";
                    Toast.makeText(getActivity(), "点击了去拍照", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri uri = Uri.fromFile(new File(picPath));
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(intent, 1);
                }

                @Override
                public void album() {
                    Intent intent1 = new Intent(Intent.ACTION_PICK);
                    intent1.setType("image/*");
                    startActivityForResult(intent1, 0);
                }

                @Override
                public void cancle() {
                    fragment.dismiss();
                }
            });
        } else {
            rlThree.setVisibility(View.GONE);
        }

    }

    public void initListeners() {
        ivUserhead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!UserInfo.userId.equals("")) {
                    fragment.show(getFragmentManager(), "");
                } else {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }

            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.rl_goto)
    public void onViewClicked() {
        //此处加判断 当没有用户登录时候跳转不同的界面  （响应事件的应该是包裹两个tv的父布局）
        if (UserInfo.userId.equals("")) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        } else {
            Intent intent1 = new Intent(getActivity(), PersonMessageActivity.class);
            intent1.putExtra("userId", UserInfo.userId);
            startActivity(intent1);
        }

    }

    @OnClick({R.id.ll_share,
            R.id.ll_problem,
            R.id.rl_setting,
            R.id.iv_MakeCode,
            R.id.rl_sign,
            R.id.rl_messages,
            R.id.rl_care,
            R.id.rl_fans})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_share:
                Intent intent2 = new Intent(getActivity(), MyShareActivity.class);
                startActivity(intent2);
                break;
            case R.id.ll_problem:
                Intent intent4 = new Intent(getActivity(), MyProblemActivity.class);
                startActivity(intent4);
                break;
            case R.id.rl_setting:
                Intent intent3 = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent3);
                break;
            case iv_MakeCode:
                ShowCodeFragment showCodeFragment = new ShowCodeFragment();
                showCodeFragment.show(getFragmentManager(), "Show");
                break;
            case rl_sign:
                Intent intent = new Intent(getActivity(), MySignActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_messages:
                Intent intent5 = new Intent(getActivity(), MyMessagesActivity.class);
                startActivity(intent5);
                break;
            case R.id.rl_care:
                Intent intent6=new Intent(getActivity(), AttentionActivity.class);
                intent6.putExtra("otherId", UserInfo.userId);
                startActivity(intent6);
                break;
            case R.id.rl_fans:
                Intent intent7 = new Intent(getActivity(), FansActivity.class);
                intent7.putExtra("otherId", UserInfo.userId);
                startActivity(intent7);
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                fragment.dismiss();
                Log.i("哈哈", "onActivityResult: " + picPath);
                Glide.with(getActivity())
                        .load(picPath)
                        .centerCrop()
                        .transform(new GlideCircleTransform(getActivity()))
                        .into(ivUserhead);
                UploadImage(picPath);


            }
            if (requestCode == 0) {
                fragment.dismiss();
                Uri uri = data.getData();
                Log.i(TAG, "onActivityResult: " + uri);
                // 将uri 类型的地址, 转化成String 类型的地址  就是绝对路径  用于上传
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = getActivity().managedQuery(uri, proj, null, null, null);
                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                actualimagecursor.moveToFirst();
                String img_path = actualimagecursor.getString(actual_image_column_index);
                Log.i("GG", "onActivityResult: " + img_path);
                Glide.with(getActivity())
                        .load(uri)
                        .centerCrop()
                        .transform(new GlideCircleTransform(getActivity()))
                        .into(ivUserhead);
                UploadImage(img_path);


            }
        }

    }

    //上传图片只服务器先   没有使用工具类
    public void UploadImage(String path) {
        OkHttpClient okHttpClient = new OkHttpClient();
        File imagePath = new File(path);
        MediaType IMAGETYPE = MediaType.parse("image/jpeg");
        RequestBody body = RequestBody.create(IMAGETYPE, imagePath);
        String url = "https://api.leancloud.cn/1.1/files/" + System.currentTimeMillis() + ".jpg";
        Request request = new Request.Builder()
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "image/*")
                .url(url)
                .post(body)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "onResponse: " + result);
                //上传成功后要修改头像
                try {
                    JSONObject object = new JSONObject(result);
                    String url = (String) object.get("url");
                    updatePro(url);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //修改用户头像
    public void updatePro(String url) {
        OkHttpClient client = new OkHttpClient();
        UpdateProBean bean = new UpdateProBean(UserInfo.userId, url);
        String url1 = "https://leancloud.cn:443/1.1/functions/updateMeheadProtrait";
        Request request = HTTPUtils.requestPost(bean, url1);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "onResponse: " + result);

            }
        });
    }

    //    获取个人用户信息  请求次数过多  应该放在懒加载中
    public void getUserInfo(String userid) {
        PostMethods.getUserInfo(userid, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Log.e("个人信息", "onResponse: " + result);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object = new JSONObject(result);
                            JSONObject result = object.getJSONObject("result");
                            JSONObject author = result.getJSONObject("author");
                            tvLogin.setText(author.getString("username"));
                            tvSign.setText(author.getString("signature"));
                            Glide.with(getActivity()).load(author.getString("headProtrait")).centerCrop().transform(new GlideCircleTransform(getActivity())).into(ivUserhead);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }
}
